const helmet = require('helmet');
const rateLimit = require('express-rate-limit');

const securityConfig = (app) => {
  // 基础安全头
  app.use(helmet());

  // 速率限制
  const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15分钟
    max: 100, // 限制每个IP 100次请求
    message: { error: '请求过于频繁，请稍后再试' }
  });
  app.use('/api/', limiter);

  // XSS 防护
  app.use(helmet.xssFilter());

  // 禁用 X-Powered-By 头
  app.disable('x-powered-by');

  // CORS 配置
  app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', process.env.ALLOWED_ORIGINS);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
    next();
  });
};

module.exports = securityConfig;